<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left">用户管理</div>
    </div>
    <div class="ci_note">
      <DescriptionBlock data="展示管理员下的用户列表" />
    </div>
    <div class="ci_des">
      <div style="display: flex">
        <el-button plain @click="showInvitation">创建用户</el-button>
      </div>
      <div style="display: flex">
        <!-- <el-select
          v-model="searchUserStatus"
          clearable
          placeholder="请选择用户状态"
          style="margin-right: 10px"
        >
          <el-option label="正常" value="1" />
          <el-option label="停用" value="0" />
        </el-select>-->
        <!-- 搜索框 -->
        <el-input
          style="margin-right: 10px"
          class="ci_input"
          v-model="nickName"
          clearable
          placeholder="请输入昵称查询"
        ></el-input>
        <el-input
          style="margin-right: 10px"
          class="ci_input"
          v-model="userName"
          clearable
          placeholder="请输入用户名查询"
        ></el-input>
        <el-select
          v-model="searchUserType"
          clearable
          placeholder="请选择用户类型"
          style="margin-right: 10px"
        >
          <el-option label="普通用户" value="1" />
          <el-option label="发证方用户" value="2" />
          <el-option label="企业用户" value="3" />
        </el-select>

        <!-- <el-input
          style="margin-right: 10px"
          class="ci_input"
          clearable
          v-model="email"
          placeholder="请输入邮箱查询"
        ></el-input>-->
        <div @click="search">
          <!-- <Search class="iconfont__header_icon" /> -->
          <el-button plain>查询</el-button>
        </div>
        <!-- <div class="iconfont icon-zhongzhireset" @click="fresh">
          <RefreshRight class="iconfont__header_icon" />
        </div>-->
      </div>
    </div>
    <div class="ci_content">
      <div class="table_list">
        <div class="tl_table">
          <el-table
            v-loading="pictLoading"
            :data="tableData"
            height="100%"
            width="100%"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableCellStyle"
          >
            <el-table-column prop="id" label="编号" width="120">
              <template v-slot="scope">
                <el-tooltip effect="light" :content="scope.row.id" placement="top">
                  <div class="ellipsis">{{ scope.row.id }}</div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="用户名" width="180" />
            <el-table-column prop="nickName" label="昵称" width="180" />
            <el-table-column prop="userType" label="用户类型">
              <template v-slot="scope">
                {{
                scope.row.userType === "1"
                ? "普通用户"
                : scope.row.userType === "2"
                ? "发证方用户"
                : scope.row.userType === "3"
                ? "企业用户" :
                "--"
                }}
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column prop="updatedTime" label="更新时间" />
            <el-table-column prop label="操作">
              <template v-slot="scope">
                <div class="center_start">
                  <span
                    @click="editPwd(scope)"
                    style="font-size: 12px; cursor: pointer; color: #409eff"
                  >修改密码</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="tl_table_pagination">
          <el-pagination
            background
            @size-change="handleSizeChange"
            :hide-on-single-page="page.isPageHide"
            @current-change="handleCurrentChange"
            :current-page.sync="page.pageNo"
            :page-size="page.pageSize"
            :page-sizes="[10, 15, 20, 30]"
            layout="total, prev, pager, next, sizes"
            :total="page.totalCount"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :width="dialogWidth"
      title="创建用户"
      :close-on-click-modal="false"
      :modelValue="dialogVisible"
      :destroy-on-close="true"
      @close="clearForm"
    >
      <div>
        <el-form
          label-position="right"
          ref="addUserFormRef"
          label-width="120px"
          :model="addUserForm"
          :rules="rules"
        >
          <el-form-item label="用户类型：" prop="userType">
            <el-select v-model="addUserForm.userType" clearable placeholder="请选择用户类型">
              <el-option label="普通用户" value="1" />
              <el-option label="发证方用户" value="2" />
              <el-option label="企业用户" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名：" prop="userName">
            <el-input v-model="addUserForm.userName" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="昵称：" prop="nickName">
            <el-input v-model="addUserForm.nickName" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="pwd">
            <el-input v-model="addUserForm.pwd" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="newPassword">
            <el-input
              type="password"
              show-password
              v-model="addUserForm.newPassword"
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer center">
        <el-button @click.prevent="inviteMember" type="primary" :loading="isLoading">确定</el-button>
        <el-button plain @click="userCancel">取消</el-button>
      </div>
    </el-dialog>
    <ResetUserPwd :showDialog="editDialogResetPwd" :id="editId" @cancel="cancelReset"></ResetUserPwd>
  </div>
</template>

<script setup>
import { DescriptionBlock, StatusTag } from "@/components/index";
import { tableHeaderStyle, tableCellStyle } from "@/utils/tableStyle";
import { stringToDate } from "@/utils/tool";
import { getUsersList, addUsers } from "@/api/userAdmin";
import {
  isValidPhone,
  isValidEmail,
  isValidPwd,
  nameValidator
} from "@/utils/validate";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ResetUserPwd } from "../../components/index";
const pictLoading = ref(false);
const searchUserType = ref("");
const userName = ref("");
const nickName = ref("");
const page = reactive({
  pageSize: 10,
  pageNo: 1,
  isPageHide: false,
  totalPage: 0,
  totalCount: 0
});
const dialogWidth = ref("600px");
const dialogVisible = ref(false);
const editDialogResetPwd = ref(false);
const editId = ref("");
const addUserForm = reactive({
  userType: "",
  userName: "",
  nickName: "",
  pwd: "",
  newPassword: ""
});
const addUserFormRef = ref("addUserForm");
const isLoading = ref(false);

/** 用户名校验 */
const validateUserName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("用户名不能为空"));
  } else {
    // 校验用户名
    if (!nameValidator(value)) {
      rule.message =
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
/** 昵称校验 */
const validateNickName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("昵称不能为空"));
  } else {
    // 校验昵称
    if (!nameValidator(value)) {
      rule.message =
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
/** 密码校验 */
const validatePwd = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else {
    // 校验密码
    if (!isValidPwd(value)) {
      rule.message =
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
/** 再次输入密码校验 */
const validateNewPwd = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else {
    // 校验密码
    if (!isValidPwd(value)) {
      rule.message =
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合";
      callback(new Error());
    } else if (addUserForm.pwd !== addUserForm.newPassword) {
      rule.message = "请确认两次密码是否一致";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
const rules = reactive({
  userType: [{ required: true, message: "请选择用户类型" }],
  userName: [
    {
      required: true,
      validator: validateUserName,
      message:
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'"
    },
    {
      min: 2,
      max: 36,
      message:
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'",
      trigger: "blur"
    }
  ],
  nickName: [
    {
      required: true,
      validator: validateNickName,
      message:
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'"
    },
    {
      min: 2,
      max: 36,
      message:
        "2-36位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'",
      trigger: "blur"
    }
  ],
  pwd: [
    {
      required: true,
      validator: validatePwd,
      message:
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合",
      trigger: "blur"
    },
    {
      min: 8,
      max: 64,
      message:
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合",
      trigger: "blur"
    }
  ],
  newPassword: [
    {
      required: true,
      validator: validateNewPwd,
      message: "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合"
    }
  ]
});
const tableData = ref([]);
const search = () => {
  getUserList();
};
const editPwd = item => {
  editId.value = item.row.id;
  editDialogResetPwd.value = true;
};
const cancelReset = () => {
  editDialogResetPwd.value = false;
};
const handleSizeChange = val => {
  page.pageNo = 1;
  page.pageSize = val;
  getUserList();
};
const handleCurrentChange = val => {
  page.pageNo = val;
  getUserList();
};
const showInvitation = () => {
  dialogVisible.value = true;
};
const setDialogWidth = () => {
  let val = document.body.clientWidth * 0.6;
  const def = 600; // 默认宽度
  if (val < def) {
    dialogWidth.value = "60%";
  } else {
    dialogWidth.value = def + "px";
  }
};
const clearForm = () => {
  dialogVisible.value = false;
  addUserFormRef.value?.resetFields();
};
const inviteMember = () => {
  addUserFormRef.value?.validate(async valid => {
    if (valid) {
      isLoading.value = true;
      let parmars = {
        ...addUserForm
      };
      // delete[parmars]
      delete parmars["newPassword"];
      const { success, msg } = await addUsers(parmars);
      if (success) {
        isLoading.value = false;
        dialogVisible.value = false;
        ElMessage.success(msg || "创建成功");
        getUserList();
      } else {
        isLoading.value = false;
        ElMessage.success(msg || "邀请失败,请稍后再试");
      }
    } else {
      return false;
    }
  });
};
const userCancel = () => {
  dialogVisible.value = false;
  // clearForm();
};
const getUserList = () => {
  let parmars = {
    pageNum: page.pageNo,
    pageSize: page.pageSize,
    userType: searchUserType.value,
    userName: userName.value,
    nickName: nickName.value
  };
  pictLoading.value = true;
  getUsersList(parmars)
    .then(res => {
      if (res.success && res.data) {
        pictLoading.value = false;
        tableData.value = res.data.list || [];
        page.totalCount = res.data.totalCount;
      } else {
        pictLoading.value = false;
      }
    })
    .catch(err => {
      ElMessage.error(err.msg);
      pictLoading.value = false;
    });
};
onMounted(() => {
  setDialogWidth();
  getUserList();
});
</script>
<style lang="scss" scoped>
@import "../../assets/css/list.scss";
@import "../../assets/css/position.scss";

.content_index {
  :deep.el-input {
    width: 90%;
    max-width: 400px;
  }
  :deep .iconfont__header_icon {
    width: 16px;
    margin-top: 8px;
  }
  .title_personal {
    font-size: 16px;
    font-weight: 700;
  }
  .tl_table_pagination {
    width: 100%;
    display: flex;
    justify-content: end;
    padding-right: 16px;
  }
}
.content_index {
  :deep.el-select {
    width: 95%;
    border-radius: 0;

    :deep .el-input {
      width: 95%;
      border-radius: 0 !important;
    }
    .el-input__suffix {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      border-radius: 0;
      font-size: 12px;
    }
  }
}

.aitem {
  cursor: pointer;
  color: #2186fb;
}

.nodata_tips {
  margin-left: 5px;
  color: #2186fb;
  cursor: pointer;
}
</style>